const { UnitConverter, CONVERSION_UNITS } = require('../../../utils/converter');

Page({
  data: {
    currentCategory: 'length',
    categories: [
      { key: 'length', name: '长度' },
      { key: 'weight', name: '重量' },
      { key: 'temperature', name: '温度' },
      { key: 'area', name: '面积' },
      { key: 'volume', name: '体积' },
      { key: 'speed', name: '速度' },
      { key: 'time', name: '时间' }
    ],
    fromUnit: 'm',
    toUnit: 'km',
    fromValue: '1',
    toValue: '0.001',
    units: [],
    history: []
  },

  onLoad() {
    this.converter = new UnitConverter();
    this.updateUnits();
    this.loadHistory();
  },

  // 切换转换类别
  switchCategory(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      currentCategory: category
    });
    this.updateUnits();
    this.convert();
  },

  // 更新单位列表
  updateUnits() {
    const category = this.data.currentCategory;
    const categoryData = CONVERSION_UNITS[category];
    
    if (categoryData && categoryData.units) {
      const units = Object.keys(categoryData.units).map(key => ({
        key,
        name: categoryData.units[key].name
      }));
      
      this.setData({
        units,
        fromUnit: units[0].key,
        toUnit: units[1] ? units[1].key : units[0].key
      });
    } else if (category === 'temperature') {
      const units = [
        { key: 'celsius', name: '摄氏度' },
        { key: 'fahrenheit', name: '华氏度' },
        { key: 'kelvin', name: '开尔文' }
      ];
      
      this.setData({
        units,
        fromUnit: 'celsius',
        toUnit: 'fahrenheit'
      });
    }
  },

  // 输入数值
  onInputValue(e) {
    const value = e.detail.value;
    this.setData({
      fromValue: value
    });
    this.convert();
  },

  // 选择源单位
  selectFromUnit(e) {
    const unit = e.currentTarget.dataset.unit;
    this.setData({
      fromUnit: unit
    });
    this.convert();
  },

  // 选择目标单位
  selectToUnit(e) {
    const unit = e.currentTarget.dataset.unit;
    this.setData({
      toUnit: unit
    });
    this.convert();
  },

  // 交换单位
  swapUnits() {
    const { fromUnit, toUnit, fromValue, toValue } = this.data;
    this.setData({
      fromUnit: toUnit,
      toUnit: fromUnit,
      fromValue: toValue,
      toValue: fromValue
    });
  },

  // 执行转换
  convert() {
    const { currentCategory, fromUnit, toUnit, fromValue } = this.data;
    
    if (!fromValue || isNaN(fromValue)) {
      this.setData({ toValue: '0' });
      return;
    }
    
    const value = parseFloat(fromValue);
    let result;
    
    try {
      if (currentCategory === 'temperature') {
        result = this.converter.convertTemperature(value, fromUnit, toUnit);
      } else {
        result = this.converter.convertUnit(value, fromUnit, toUnit, currentCategory);
      }
      
      // 格式化结果
      const formattedResult = this.formatResult(result);
      
      this.setData({
        toValue: formattedResult
      });
      
      // 添加到历史记录
      this.addToHistory({
        category: currentCategory,
        fromValue: value,
        fromUnit,
        toValue: formattedResult,
        toUnit,
        timestamp: Date.now()
      });
      
    } catch (error) {
      console.error('转换错误:', error);
      this.setData({ toValue: '错误' });
    }
  },

  // 格式化结果
  formatResult(result) {
    if (isNaN(result) || !isFinite(result)) {
      return '错误';
    }
    
    // 对于非常大或非常小的数字，使用科学记数法
    if (Math.abs(result) >= 1e10 || (Math.abs(result) < 1e-6 && result !== 0)) {
      return result.toExponential(6);
    }
    
    // 对于普通数字，保留适当的小数位数
    if (Number.isInteger(result)) {
      return result.toString();
    }
    
    // 最多保留8位小数
    return parseFloat(result.toPrecision(8)).toString();
  },

  // 添加到历史记录
  addToHistory(item) {
    let history = this.data.history;
    
    // 避免重复记录
    const isDuplicate = history.some(h => 
      h.category === item.category &&
      h.fromValue === item.fromValue &&
      h.fromUnit === item.fromUnit &&
      h.toUnit === item.toUnit
    );
    
    if (!isDuplicate) {
      history.unshift(item);
      
      // 最多保存20条记录
      if (history.length > 20) {
        history = history.slice(0, 20);
      }
      
      this.setData({ history });
      this.saveHistory();
    }
  },

  // 使用历史记录
  useHistory(e) {
    const item = e.currentTarget.dataset.item;
    
    // 切换到对应类别
    if (item.category !== this.data.currentCategory) {
      this.setData({
        currentCategory: item.category
      });
      this.updateUnits();
    }
    
    this.setData({
      fromUnit: item.fromUnit,
      toUnit: item.toUnit,
      fromValue: item.fromValue.toString(),
      toValue: item.toValue
    });
  },

  // 清除历史记录
  clearHistory() {
    this.setData({ history: [] });
    this.saveHistory();
    wx.showToast({
      title: '历史记录已清除',
      icon: 'success'
    });
  },

  // 保存历史记录
  saveHistory() {
    wx.setStorageSync('converter_history', this.data.history);
  },

  // 加载历史记录
  loadHistory() {
    const history = wx.getStorageSync('converter_history') || [];
    this.setData({ history });
  },

  // 复制结果
  copyResult() {
    const { toValue, toUnit } = this.data;
    const unitName = this.data.units.find(u => u.key === toUnit)?.name || toUnit;
    
    wx.setClipboardData({
      data: `${toValue} ${unitName}`,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 快速输入常用数值
  quickInput(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      fromValue: value
    });
    this.convert();
  },

  // 清除输入
  clearInput() {
    this.setData({
      fromValue: '',
      toValue: '0'
    });
  }
});